package com.zhanghp.class03;

import com.zhanghp.refer.ListNode;

/**
 * <h1>合并两个有序链表，合并后也要求升序</h1>
 * @author zhanghp
 * @since 2023/10/20 19:54
 */
public class Code06_MergeSortedLinkedList {

    public static void main(String[] args) {

    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2){
        if (l1 ==null || l2 ==null) {
            return l1 == null ? l2 : l1;
        }
        ListNode head = l1.val > l2.val ? l2 : l1;
        ListNode cur1 = head.next;
        ListNode cur2 = head == l1 ? l2 : l1;
        ListNode pre = head;
        while (cur1 != null && cur2 != null){
            if (cur1.val > cur2.val) {
                pre.next = cur2;
                cur2 = cur2.next;
            }else{
                pre.next = cur1;
                cur1 = cur1.next;

            }
            pre = pre.next;
        }
        pre.next = cur1 != null ? cur1 : cur2;
        return head;
    }
}
